#include "../header/Client.h"

ConnectInfo *Client::info = nullptr;


Client::~Client() = default;

void Client::startClient() {
    info = connectSever();

    if (info == nullptr) {
        getchar();
        system("pause");
        pthread_exit(nullptr);
    }
}

void Client::endClient() {
    close(info->client_fd);
}

string Client::sendMessageToSever(const string& message) {
    char buffer[1024];
    int client_fd = info->client_fd;

    sprintf(buffer, "%s", NetworkTools::encryptionMessage(message).c_str());
    send(client_fd, buffer, strlen(buffer), 0);

    memset(buffer, 0, sizeof(buffer));
    int length = recv(info->client_fd, buffer, sizeof(buffer), 0);
    string response;

    if (0 < length) {
        response = "Server Say: " + NetworkTools::decryptionMessage(string(buffer));

    } else if (0 == length) {
        response = "Server Is Disconnect!";

    } else {
        response = "Receive Fail!";
    }

    return response;
}

ConnectInfo *Client::connectSever() {
    // 1.创建通信的套接字
    int client_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_IP);
    if (client_fd == -1) {
        perror("Socket Create Fail!\n");
        return nullptr;
    }

    // 2.连接服务器
    struct sockaddr_in server_address;
    server_address.sin_family = AF_INET;
    server_address.sin_port = htons(SERVER_PORT);
    inet_pton(AF_INET, SERVER_IP, &server_address.sin_addr.s_addr);
    int ret = connect(client_fd, (struct sockaddr *) &server_address, sizeof(server_address));
    if (ret == -1) {
        close(client_fd);
        printf("Connect Server Fail!\n");
        return nullptr;

    } else {
        printf("Connect Server Success!\n");
    }

    return new ConnectInfo(client_fd, server_address);
}


